package cn.jietuo.juc.c_007_reentrant;

import javax.management.relation.RelationNotFoundException;
import java.sql.Time;
import java.util.concurrent.*;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2021/1/11
 * @description: 旅行团一起办理签证，然后一起出发
 */
public class T05_Cyclibarrier_Travel {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(4,new TourGuide());
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        executorService.execute(new TravelTask("张三",cyclicBarrier));
        executorService.execute(new TravelTask("李四",cyclicBarrier));
        executorService.execute(new TravelTask("王五",cyclicBarrier));
        executorService.execute(new TravelTask("赵六",cyclicBarrier));
    }

    static class TravelTask implements Runnable{

        /** 游客名称*/
        private String name;

        private CyclicBarrier cyclicBarrier;

        public TravelTask(String name,CyclicBarrier cyclicBarrier){
            this.name = name;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            System.out.println(name + "将签证给到导游一起去办签证咯");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("导游办理完签证咯，这是你的，" + name);
        }
    }

    static class TourGuide implements Runnable{

        @Override
        public void run() {
            System.out.println("导游办理签证中...");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
